package com.tianqu.tms.core.util;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.dao.TmsConfigureDao;
import com.tianqu.tms.dao.TmsDao;

/**
 * 系统配置参数的读取
 * @author liugang
 */
public class Registry implements TmsConstants {

	private static Logger logger = Logger.getLogger(Registry.class);
	
	// 配置的名称
	private static final String PROPERTY_NAME = "tms";

	private static Map map = null;
	static {
		map = Collections.synchronizedMap(new HashMap());

		try{
			java.util.ResourceBundle rb = java.util.ResourceBundle.getBundle(PROPERTY_NAME);
			map.put(PROPERTIES, rb);

			Enumeration element = rb.getKeys();
			String strKey = null;
			while (element.hasMoreElements()) {
				strKey = (String)element.nextElement();
				map.put(strKey, rb.getString(strKey));
			}
			
			//core
			loadInstances(rb,"core");
			String registryType = rb.getString("registry.type");

			//www
			loadInstances(rb,registryType);
			
		}catch(Exception e){
			throw new Error("failed to load Registry: " + e, e);
		}
	}
	/**
	 * 
	 * @param rb
	 * @param registryType
	 */
	private static void loadInstances(java.util.ResourceBundle rb,String registryType){
		String names = rb.getString("registry."+registryType+".names");
		StringTokenizer st = new StringTokenizer(names, ",");
		while (st.hasMoreTokens()) {
			String name = st.nextToken();
			String className = rb.getString("registry." + name + ".className");
			
			logger.debug("Registry: name=" + name + ",className="+ className);
			try{
			Object o = Class.forName(className).newInstance();
			map.put(name, o);
			}catch(Exception ee){
				logger.error("load Class error("+"Registry: name=" + name + ",className="+ className+")");
				ee.printStackTrace();
			}
		}
	}

	/**
	 * check get
	 * 
	 * @param name
	 * @return object
	 */
	public static Object get(String name) {
		return map.get(name);
	}
	
	/**
	 * @param k
	 * @return
	 */
	public static String getConfig(String k) {
		String v = (String)map.get(k);
		return StringUtil.isNotBlank(v)?v:getConfigFromDb(k);
	}
	
	 
	/**
	 * @param k
	 * @return
	 */
	public static String getConfigFromDb(String k){
	 String v = null;
	 try {
		 TmsConfigureDao dao = (TmsConfigureDao) TmsDao.getInstance(TmsDao.TMS_CONFIGURE);
		 v = dao.getConfig(k);
		 if(StringUtil.isNotBlank(v)) map.put(k, v);
		} catch (Exception e) {
			logger.error("getConfigFromDb error.",e);
			v = null;
		}
	    logger.debug("getConfigFromDb: name=" + k + ",value="+ v);
	    return v;
	 }

	/**
	 * check set
	 * 
	 * @param name
	 * @param obj
	 */
	public static void set(String name, Object obj) {
		map.put(name, obj);
	}
}